import { useState, Suspense } from 'react'
import { Canvas } from '@react-three/fiber'
import { useGLTF, OrbitControls, PerspectiveCamera } from '@react-three/drei'
import { getModelFile, updateModel } from '../api'
import ModelPreview from './ModelPreview'
import * as THREE from 'three'

// 3D模型缩略图组件
function ModelThumbnail({ url }) {
    const { scene } = useGLTF(url)
    const clonedScene = scene.clone()

    // 计算模型的边界框并居中
    const box = new THREE.Box3().setFromObject(clonedScene)
    const center = box.getCenter(new THREE.Vector3())
    const size = box.getSize(new THREE.Vector3())

    // 将模型移到中心
    clonedScene.position.sub(center)

    // 根据模型大小自动调整缩放
    const maxDim = Math.max(size.x, size.y, size.z)
    const scale = maxDim > 0 ? 2.5 / maxDim : 1

    return (
        <primitive
            object={clonedScene}
            scale={scale}
        />
    )
}

function ModelList({ models, onDelete, onRefresh }) {
    const [editingModel, setEditingModel] = useState(null)
    const [editName, setEditName] = useState('')
    const [editDescription, setEditDescription] = useState('')
    const [previewModel, setPreviewModel] = useState(null)

    const handleEditClick = (model) => {
        setEditingModel(model.id)
        setEditName(model.name || '')
        setEditDescription(model.description || '')
    }

    const handleSave = async (model) => {
        if (!editName.trim()) {
            alert('模型名称不能为空')
            return
        }

        try {
            await updateModel(model.id, {
                name: editName.trim(),
                description: editDescription.trim()
            })
            setEditingModel(null)
            setEditName('')
            setEditDescription('')
            onRefresh()
        } catch (err) {
            alert('更新失败：' + (err.response?.data?.error || '未知错误'))
        }
    }

    const handleCancelEdit = () => {
        setEditingModel(null)
        setEditName('')
        setEditDescription('')
    }

    const handlePreview = (model) => {
        setPreviewModel({
            ...model,
            url: getModelFile(model.id)
        })
    }

    if (!models || models.length === 0) {
        return (
            <div className="text-center py-12 text-gray-400">
                <div className="text-6xl mb-4">📦</div>
                <p>暂无模型，点击上方按钮生成你的第一个 3D 模型吧！</p>
            </div>
        )
    }

    const getStatusConfig = (status) => {
        const configs = {
            generating: {
                text: '生成中...',
                bgColor: 'bg-yellow-600/20',
                textColor: 'text-yellow-400',
                borderColor: 'border-yellow-600/30',
                icon: '⏳',
                gradient: 'from-yellow-600/20 to-yellow-800/20'
            },
            completed: {
                text: '已完成',
                bgColor: 'bg-green-600/20',
                textColor: 'text-green-400',
                borderColor: 'border-green-600/30',
                icon: '📦',
                gradient: 'from-blue-600/20 to-blue-800/20'
            },
            failed: {
                text: '生成失败',
                bgColor: 'bg-red-600/20',
                textColor: 'text-red-400',
                borderColor: 'border-red-600/30',
                icon: '❌',
                gradient: 'from-red-600/20 to-red-800/20'
            }
        }
        return configs[status] || configs.completed
    }

    return (
        <>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {models.map(model => {
                    const statusConfig = getStatusConfig(model.status)
                    const isEditing = editingModel === model.id

                    return (
                        <div key={model.id} className="card hover:border-blue-600/30 transition-all duration-200 group">
                            {/* Preview - 可点击预览 */}
                            <div
                                className={`h-48 rounded-lg bg-gradient-to-br ${statusConfig.gradient} mb-4 transition-all duration-200 relative overflow-hidden ${model.status === 'completed' ? 'cursor-pointer group-hover:scale-105' : 'flex items-center justify-center text-6xl'
                                    }`}
                                onClick={() => model.status === 'completed' && handlePreview(model)}
                            >
                                {/* 已完成的模型显示3D预览 */}
                                {model.status === 'completed' ? (
                                    <>
                                        <Canvas>
                                            <PerspectiveCamera makeDefault position={[0, 0, 5]} fov={50} />
                                            <ambientLight intensity={1} />
                                            <pointLight position={[10, 10, 10]} intensity={1} />
                                            <pointLight position={[-10, -10, -10]} intensity={0.5} />
                                            <Suspense fallback={null}>
                                                <ModelThumbnail url={getModelFile(model.id)} />
                                            </Suspense>
                                            <OrbitControls
                                                enableZoom={false}
                                                enablePan={false}
                                                autoRotate
                                                autoRotateSpeed={2}
                                            />
                                        </Canvas>
                                        <div className="absolute inset-0 bg-black/0 group-hover:bg-black/40 rounded-lg flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-200 pointer-events-none">
                                            <span className="text-white text-lg font-medium">👁️ 预览</span>
                                        </div>
                                    </>
                                ) : (
                                    // 生成中或失败显示图标
                                    statusConfig.icon
                                )}
                            </div>

                            {/* Info */}
                            <div className="space-y-3">
                                {/* 标题和状态 - 始终显示 */}
                                {!isEditing && (
                                    <div className="flex justify-between items-start gap-2">
                                        <h3 className="text-lg font-semibold text-gray-100 truncate flex-1">
                                            {model.name}
                                        </h3>
                                        <span className={`px-2 py-1 rounded text-xs font-medium ${statusConfig.bgColor} ${statusConfig.textColor} border ${statusConfig.borderColor} whitespace-nowrap`}>
                                            {statusConfig.text}
                                        </span>
                                    </div>
                                )}

                                {/* 编辑模式 - 编辑名字和描述 */}
                                {isEditing && (
                                    <>
                                        <div className="flex justify-between items-start gap-2 mb-2">
                                            <span className="text-sm text-gray-400">编辑模型信息</span>
                                            <span className={`px-2 py-1 rounded text-xs font-medium ${statusConfig.bgColor} ${statusConfig.textColor} border ${statusConfig.borderColor} whitespace-nowrap`}>
                                                {statusConfig.text}
                                            </span>
                                        </div>
                                        <div className="space-y-2">
                                            <input
                                                type="text"
                                                value={editName}
                                                onChange={(e) => setEditName(e.target.value)}
                                                className="input-field text-sm"
                                                placeholder="模型名称"
                                                autoFocus
                                            />
                                            <textarea
                                                value={editDescription}
                                                onChange={(e) => setEditDescription(e.target.value)}
                                                className="input-field resize-none text-sm"
                                                rows="3"
                                                placeholder="模型描述（可选）"
                                            />
                                            <div className="flex gap-2">
                                                <button
                                                    onClick={() => handleSave(model)}
                                                    className="flex-1 px-3 py-1.5 bg-blue-600/20 hover:bg-blue-600/30 text-blue-400 hover:text-blue-300 rounded-lg text-sm font-medium transition-all duration-200 border border-blue-600/30"
                                                >
                                                    保存
                                                </button>
                                                <button
                                                    onClick={handleCancelEdit}
                                                    className="flex-1 px-3 py-1.5 bg-dark-700 hover:bg-dark-600 text-gray-400 hover:text-gray-300 rounded-lg text-sm font-medium transition-all duration-200"
                                                >
                                                    取消
                                                </button>
                                            </div>
                                        </div>
                                    </>
                                )}

                                {/* 描述显示模式 */}
                                {!isEditing && (
                                    <>
                                        <div className="flex items-start gap-2">
                                            <p className="text-sm text-gray-400 line-clamp-2 flex-1">
                                                {model.description || '暂无描述'}
                                            </p>
                                            <button
                                                onClick={() => handleEditClick(model)}
                                                className="text-gray-500 hover:text-blue-400 transition-colors text-lg flex-shrink-0"
                                                title="编辑模型信息"
                                            >
                                                ✏️
                                            </button>
                                        </div>
                                    </>
                                )}

                                {/* Actions */}
                                {!isEditing && (
                                    <div className="flex gap-2 pt-2">
                                        {model.status === 'completed' && (
                                            <>
                                                <button
                                                    onClick={() => handlePreview(model)}
                                                    className="flex-1 px-4 py-2 bg-blue-600/20 hover:bg-blue-600/30 text-blue-400 hover:text-blue-300 rounded-lg font-medium transition-all duration-200 border border-blue-600/30"
                                                >
                                                    预览
                                                </button>
                                                <a
                                                    href={getModelFile(model.id)}
                                                    download={`${model.name}.glb`}
                                                    className="flex-1 px-4 py-2 bg-green-600/20 hover:bg-green-600/30 text-green-400 hover:text-green-300 rounded-lg font-medium transition-all duration-200 border border-green-600/30 text-center"
                                                >
                                                    下载
                                                </a>
                                            </>
                                        )}
                                        {model.status === 'generating' && (
                                            <div className="flex-1 px-4 py-2 bg-yellow-600/20 text-yellow-400 rounded-lg font-medium border border-yellow-600/30 flex items-center justify-center gap-2">
                                                <div className="inline-block animate-spin rounded-full h-4 w-4 border-2 border-yellow-400 border-t-transparent"></div>
                                                <span>AI 生成中...</span>
                                            </div>
                                        )}
                                        <button
                                            onClick={() => onDelete(model.id)}
                                            className="btn-danger"
                                        >
                                            删除
                                        </button>
                                    </div>
                                )}
                            </div>
                        </div>
                    )
                })}
            </div>

            {/* 模型预览模态框 */}
            {previewModel && (
                <ModelPreview
                    model={previewModel}
                    onClose={() => setPreviewModel(null)}
                />
            )}
        </>
    )
}

export default ModelList
